package se.webbzon.oschi01.action;

import java.awt.Component;
import java.awt.event.ActionEvent;

import javax.swing.Icon;
import javax.swing.JOptionPane;

import se.webbzon.oschi01.command.Command;
import se.webbzon.oschi01.gui.ApplicationIconSheet;
import se.webbzon.oschi01.gui.ApplicationIcon;
import se.webbzon.oschi01.gui.NBTIconSheet;
import se.webbzon.oschi01.nbt.Tag;
import se.webbzon.oschi01.nbt.TagFactory;
import se.webbzon.oschi01.nbt.TagGeneration;
import se.webbzon.oschi01.singleton.Singletons;

public class NBTNewAction extends DefaultAction {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -6444899595933903674L;
	
	private static final ApplicationIconSheet iconSheet = Singletons.instance(ApplicationIconSheet.class);
	private static final NBTIconSheet nbtSheet = Singletons.instance(NBTIconSheet.class);
	
	private final Component parent;
	private final Tag<?> nbtTag;
	private final TagFactory<?> factory;
	
	public NBTNewAction(Component parent, Tag<?> nbtTag, TagFactory<?> factory) {
		this.parent = parent;
		this.nbtTag = nbtTag;
		this.factory = factory;
		putValue(NAME, factory.toString());
		putValue(SMALL_ICON, nbtSheet.getIcon(factory.getId()));
	}

	@Override public void actionPerformed(ActionEvent e) {
		Tag<?> child = factory.createTag("");
		if (nbtTag.canAdopt(child))
			performCommand(new CommandImpl(nbtTag.getChildren(),child));
		else if (!nbtTag.hasChildren() && nbtTag.hasParent() && nbtTag.getParent().canAdopt(child))
			performCommand(new CommandImpl(nbtTag.getGeneration(),child));
		else {
			String message = "The new tag can not be added to the target.";
			String title = "Action not supported";
			int messageType = JOptionPane.PLAIN_MESSAGE;
			Icon icon = iconSheet.getIcon(ApplicationIcon.Error);
			JOptionPane.showMessageDialog(parent, message, title, messageType, icon);
		}
	}
	
	private final class CommandImpl implements Command {
		
		private final TagGeneration<?> target;
		@SuppressWarnings("rawtypes")
		private final Tag newTag;
		
		public CommandImpl(TagGeneration<?> target, Tag<?> newTag) {
			this.target = target;
			this.newTag = newTag;
		}

		@Override public String getName() {
			return "add " + factory.toString();
		}

		@SuppressWarnings("unchecked")
		@Override public void redo() {
			target.addSibling(newTag);
		}

		@SuppressWarnings("unchecked")
		@Override public void undo() {
			target.removeSibling(newTag);
		}
		
	}

}
